package com.fit.pages.vehicle;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.vehicle.VehicleDAO;
import com.fit.entities.Vehicle;
import com.fit.model.type.VehicleType;

@UserAccess
@AdminAccess
public class EditVehicle {

	@Property
	@Persist
	private Vehicle vehicle;
	
	@Inject
	private VehicleDAO vehicleDAO;
	
	@InjectPage
	private ManageVehicles manage;
	
	@Inject
	private Messages messages;
	
	@Property
	@Persist
	private VehicleType vehicleType;
	
	public SelectModel getTypes() {
		return new EnumSelectModel(VehicleType.class, messages);
	}
	
	Object onActivate(String chassisNumber) {
		manage.setError("");
		manage.setConfirmation("");
		Vehicle v = vehicleDAO.findByChassisNumber(chassisNumber);
		if (v != null) {
			vehicle = v;
		}
		if (vehicle == null) {
			manage.setError("Error");
			return manage;
		}
		return null;
	}

	Object onSuccess() {
		manage.setError("");
		manage.setConfirmation("");
		try {
			if (vehicleType !=null && !vehicle.getTypeOfVehicle().equalsIgnoreCase(vehicleType.toString())) {
				vehicle.setTypeOfVehicle(vehicleType.toString());
			}
			vehicleDAO.update(vehicle);
			manage.setConfirmation("Successfully edited.");
			return manage;
		} catch (Exception e) {
			manage.setError("Error.");
			return manage;
		}

	}

}
